/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.yongw.MouseMove;
import java.awt.AWTException;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.io.IOException;
import java.io.InputStream;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Platform;
import javafx.geometry.Rectangle2D;
import javafx.scene.control.TextArea;
import javafx.stage.Screen;

/**
 * 封装接受数据的工具类
 * @author 张永伟
 */
public class ReceiveDataUtil{
    private static double lastMoveX = 0, lastMoveY = 0, currentMoveX = 0, currentMoveY = 0;
    private static double phone_width = 0, phone_height = 0, computer_width = 0, computer_height = 0;
    private static double xRatio = 0, yRatio = 0;   
    private static int receiveTimes = 0;
    private static String Xdirection= "", Ydirection ="", lastXdirection = "", lastYdirection ="";
     private static Robot robot ;
    private static Format format;
    public ReceiveDataUtil(){        
    }
    /**
     * 实现接受数据并且触发各种移动鼠标操作
     * @param is 输入流
     * @param ta 展示通知的窗口
     * @throws IOException 
     */
    public static void receiveData(InputStream is, TextArea ta) throws IOException{
        try {
            if(robot ==null)//没有初始化就初始化
                robot = new Robot();            
        } catch (AWTException ex) {
            Logger.getLogger(MouseMove.class.getName()).log(Level.SEVERE, null, ex);
        }
        if(computer_width == 0 || computer_height == 0){//没有初始化就初始化
            Rectangle2D screenRectange = Screen.getPrimary().getBounds();
            computer_width = (int)screenRectange.getWidth();
            computer_height = (int)screenRectange.getHeight();
        }
        if(format == null)//没有初始化就初始化
            format = new SimpleDateFormat("YYYY年yy月dd日HH:mm:ss.SSS");     
        byte[] buffer = new byte[1024];
        if(is.read(buffer) != -1){//读取屏幕宽和高
             String s = new String(buffer);
             String []command = s.split(":");
             phone_width = Double.parseDouble(command[0]);
             phone_height=Double.parseDouble(command[1]);
             yRatio =xRatio = computer_width * 1.0 / phone_width;
         }
        while(is.read(buffer) !=-1 ){                           
            String s = new String(buffer).trim();           
            String [] stemp = s.split("[|]");//区分不同的消息命令
            for(String temp :stemp){         
                String []command = temp.split(":");
                if(command.length >= 1 && !command[0].equals("")){//收到的消息是完整的
                    if(command[0].equals("Touch") && command.length == 3){
                        lastMoveX = currentMoveX;
                        lastMoveY = currentMoveY;             
                        
                        currentMoveX = Double.parseDouble(command[1]);
                        currentMoveY = Double.parseDouble(command[2]);
                       lastXdirection = Xdirection;
                        lastYdirection = Ydirection;
                        if(lastMoveX!=0 || lastMoveY !=0){
                            Xdirection=currentMoveX>0?"右":"左";
                            Ydirection=currentMoveY>0?"下":"上"; 
                            if(!Xdirection.equals(lastXdirection) || !(Ydirection.equals(lastYdirection)))
                                 Platform.runLater(() -> ta.appendText(format.format(new Date()) + "-> 移动鼠标->"+Xdirection + Ydirection+"\n")); 
                            moveMouse(1, (currentMoveX - lastMoveX), (currentMoveY- lastMoveY));
                        }
                    }else  if(command[0].equals("LeftClick")){
                        //说明这时候鼠标已经抬起，把上次移动数据清空
                        lastMoveX = currentMoveX=0;
                        lastMoveY = currentMoveY=0;                             
                        onclickMouse("L");//单击鼠标左键
                        onRealeaseMouse("L");//抬起鼠标左键
                        Platform.runLater(() -> ta.appendText(format.format(new Date()) + "-> 点击鼠标->\n"));
                    }else if(command[0].equals("RightRelease")){
                        onRealeaseMouse("R");//抬起鼠标右键
                        Platform.runLater(() -> ta.appendText(format.format(new Date()) + "-> 右击鼠标抬起->\n"));
                    }else if(command[0].equals("LeftDown")){
                        robot.delay(490);
                        onclickMouse("L");//按下鼠标左键
                        Platform.runLater(() -> ta.appendText(format.format(new Date()) + "-> 左键按下->\n"));
                    }else if(command[0].equals("LeftRelease")){
                         onRealeaseMouse("L");//抬起鼠标右键
                        Platform.runLater(() -> ta.appendText(format.format(new Date()) + "-> 左击鼠标抬起->\n"));
                    }else if(command[0].equals("TouchEnd")){//触摸结束
                        lastMoveX = currentMoveX = 0;
                        lastMoveY = currentMoveY = 0;
                        lastXdirection = Xdirection = ""; 
                        lastYdirection = Ydirection = "";
                        Platform.runLater(() -> ta.appendText(format.format(new Date()) + "-> 移动结束->\n"));
                    }else if(command[0].equals("Slip") && command.length == 2){//滑动操作
                        lastYdirection = Ydirection;                                        
                        currentMoveY = Double.parseDouble(command[1]);
                        Ydirection=currentMoveY > 0?"下":"上";
                        if(!(Ydirection.equals(lastYdirection))){
                            Platform.runLater(() -> ta.appendText(format.format(new Date()) + "-> 滑动滑轮->="+Ydirection+"\n"));
                        }
                        if(receiveTimes++ /15 == 1){//接受15次数据移动一次，降低移动频次
                            slipMouse(currentMoveY  /Math.abs(currentMoveY));
                            receiveTimes = 0;
                        }
                    }else if(command[0].equals("RightClick")){
                        onclickMouse("R");//单击鼠标左键
                        Platform.runLater(() -> ta.appendText(format.format(new Date()) + "-> 右击鼠标->\n"));
                    }else if(command[0].equals("WHChanged") && command.length == 1){
                        if(command[1].equals("1")){//竖直屏幕
                            yRatio = xRatio = computer_width * 1.0 / phone_width;
                        }else{//横向屏幕
                            yRatio = xRatio = computer_width * 1.0 / phone_height;
                        }
                    }
                }
                buffer = new byte[1024];//影响不大
                if(temp.contains("EXIT")){
                    System.out.println("客户端退出");
                    break;
                }
            }
        }
    }
    /**
     * 移动鼠标
     * @param type 移动鼠标类型
     * @param x x坐标
     * @param y y坐标
     */
    public static void moveMouse(int type, double x, double y){
        Point p = MouseInfo.getPointerInfo().getLocation();
        double width =  p.getX() + x * xRatio;
        double height = p.getY() + y * yRatio;
        if(type == 0){
            width = x;
            height = y;
        }
        robot.mouseMove((int)width, (int)height);       
    }
    /**
     * 实现滚动滚轮
     * @param y y移动坐标
     */
    public static void slipMouse(double y){
        Point p = MouseInfo.getPointerInfo().getLocation();        
        robot.mouseWheel((int)y );      
    }
    /**
     * 实现按下鼠标
     * @param lr 按下左键还是右键
     */
    public static void onclickMouse(String lr){
        if(lr.equals("R")){//鼠标右键
            robot.mousePress(InputEvent.BUTTON3_MASK);            
        }else{//鼠标左键
            robot.mousePress(InputEvent.BUTTON1_MASK);    
        }
    }
    /**
     * 实现抬起鼠标
     * @param lr 抬起的是左键还是右键
     */
    public static void onRealeaseMouse(String lr){
        if(lr.equals("R")){
            robot.delay(10);   
            robot.mouseRelease(InputEvent.BUTTON3_MASK);
        }else{//鼠标左键
            robot.mouseRelease(InputEvent.BUTTON1_MASK);
        }
    }
}
